const TaskIncomeSchema = require('../entity/account/taskincome');
const WithdrawRecord = require('../entity/account/withdrawrecord');

const { CommonServiceError } = require('../module/error/svcerror');
const ChargeRecord = require('../entity/charge/chargerecord');

// 获取账户余额
async function getAccountPrice (areaId) {
    const TaskIncomeModel = new TaskIncomeSchema().getModel();
    const WithdrawRecordModel = new WithdrawRecord().getModel();
    // 收入总价
    const incomeData = await TaskIncomeModel.aggregate([
        { $match: { areaId: TaskIncomeSchema.toObjectId(areaId) } },
        {
            $group: {
                _id: null,
                total: { $sum: '$price' }
            }
        }
    ]);
    const incomeTotal = incomeData.length > 0 ? incomeData[0].total : 0;

    // 提现总价
    const withdrawData = await WithdrawRecordModel.aggregate([
        { $match: { areaId: TaskIncomeSchema.toObjectId(areaId) } },
        {
            $group: {
                _id: null,
                total: { $sum: '$price' }
            }
        }
    ]);
    const withdrawTotal = withdrawData.length > 0 ? withdrawData[0].total : 0;
    const returnTotal = incomeTotal - withdrawTotal;
    return returnTotal;
}

// 提现支出记录
async function withDraw (adminId, areaId, price, realPrice, description) {
    // 获取可提现金额
    const totalPrice = await getAccountPrice(areaId);
    if (price <= 0) throw new CommonServiceError('提现金额不正确');
    if (price > totalPrice) throw new CommonServiceError('可提现余额不足');

    const WithdrawRecordEntity = new WithdrawRecord();
    return await WithdrawRecordEntity.initWithdrawRecord(adminId, areaId, price, realPrice, description);
}

// 查询订单收入记录
async function incomeRecord (areaId, offset, rows) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    const TaskIncomeModel = new TaskIncomeSchema().getModel();

    // 订单收入信息
    const taskIncomeData = await TaskIncomeModel.aggregate([
        { $match: { areaId: TaskIncomeSchema.toObjectId(areaId) } },
        { $sort: { createTime: -1 } },
        { $skip: offset },
        { $limit: rows },
        {
            $lookup: {
                from: 'order',
                localField: 'orderId',
                foreignField: '_id',
                as: 'orderData'
            }
        },
        {
            $unwind: {
                path: '$orderData',
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $lookup: {
                from: 'charge_record',
                localField: 'orderId',
                foreignField: '_id',
                as: 'rechargeData'
            }
        },
        {
            $unwind: {
                path: '$rechargeData',
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $lookup: {
                from: 'user_base',
                localField: 'rechargeData.userId',
                foreignField: '_id',
                as: 'userInfo'
            }
        },
        {
            $unwind: {
                path: '$userInfo',
                preserveNullAndEmptyArrays: true
            }
        }
    ]);
    const total = await TaskIncomeModel.countDocuments({ areaId });
    return {
        taskIncomeData,
        total
    };
}

/**
 * 查询提现记录
 * @param areaId
 * @param offset
 * @param rows
 */
async function userWithdrawRecord (areaId, offset, rows) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    const WithdrawRecordModel = new WithdrawRecord().getModel();
    const withDrawRecordData = await WithdrawRecordModel.find({ areaId }).sort({ createTime: -1 }).skip(offset).limit(rows);
    const withDrawTotal = await WithdrawRecordModel.countDocuments({ areaId });
    return {
        withDrawRecordData,
        withDrawTotal
    };
}

// 查询充值记录收入
async function rechargeRecord (areaId, offset, rows) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    const ChargeRecordModel = new ChargeRecord().getModel();
}

module.exports = {
    getAccountPrice,
    withDraw,
    incomeRecord,
    userWithdrawRecord,
    rechargeRecord
};
